var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.width;

var img = new Image();
img.crossOrigin = 'anonymous';
img.src = '../images/pattern.png';
img.onload = function() {
    draw();
}

var draw = function () {    
    ctx.clearRect(0, 0, width, height);
    // 渐变和纹理
    var gradient, pattern;
    // 创建材质canvas
    var canvasPattern = document.createElement('canvas');
    var contextUnder = canvasPattern.getContext('2d');
    canvasPattern.width = width;
    canvasPattern.height = height;

    // 创建渐变canvas
    var canvasGradient = document.createElement('canvas');
    var contextOver = canvasGradient.getContext('2d');
    canvasGradient.width = width;
    canvasGradient.height = height;
    // 绘制渐变对象
    gradient = contextOver.createLinearGradient(0, 0, 0, height);
    gradient.addColorStop(0, 'red');
    gradient.addColorStop(1, 'red');

    // 纹理对象，img指纹理图片对象
    pattern = contextUnder.createPattern(img, 'no-repeat');
    contextUnder.fillStyle = pattern;
    contextUnder.fillRect(0, 0, width, height);
    // 应用渐变
    contextOver.fillStyle = gradient;
    contextOver.fillRect(0, 0, width, height);
    // 叠加canvas
    contextOver.blendOnto(contextUnder, 'overlay'); //内部的getImageData函数，必须要支持本地跨域

    // 给当前context创建pattern
    pattern = ctx.createPattern(canvasPattern, 'no-repeat');
    
    // 绘制文本
    ctx.fillStyle = pattern;
    ctx.textBaseline = 'miiddle';
    ctx.font = 'normal normal bold 60px arial';
    ctx.fillText('画布纹理叠加', 0, 60);
};